package com.hunit.mqtt_dome.emqx;

import cn.hutool.json.JSONObject;
import com.hunit.mqtt_dome.service.MqttMessageReceiveService;
import com.hunit.mqtt_dome.websocket.WebSocket;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Description : MQTT回调处理类
 * @Author : Sherlock
 * @Date : 2023/8/1 16:30
 */
@Component
public class MqttAcceptCallback implements MqttCallback {

    private static final Logger logger = LoggerFactory.getLogger(MqttAcceptCallback.class);

    // 使用ApplicationContext延迟注入MqttMessageReceiveService，避免循环依赖
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private WebSocket webSocket;
    
    private MqttMessageReceiveService mqttMessageReceiveService;
    
    // 静态实例，用于回调方法中访问
    private static MqttAcceptCallback instance;
    
    @PostConstruct
    public void init() {
        instance = this;
    }

    /**
     * 连接丢失后，一般在这里面进行重连
     *
     * @param cause 原因
     */
    @Override
    public void connectionLost(Throwable cause) {
        logger.info("连接断开，可以做重连");
        cause.printStackTrace();
    }

    /**
     * 消息到达处理
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        String message = new String(mqttMessage.getPayload());
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + message);
        JSONObject jsonObject = new JSONObject(message);
        webSocket.sendAllMessage(message);
        // 在这里处理接收到的消息
        processMessage(topic, message);
    }

    /**
     * 消息处理
     *
     * @param topic   主题
     * @param message 消息内容
     */
    private void processMessage(String topic, String message) {
        // 延迟加载MqttMessageReceiveService
        if (mqttMessageReceiveService == null && applicationContext != null) {
            try {
                mqttMessageReceiveService = applicationContext.getBean(MqttMessageReceiveService.class);
            } catch (Exception e) {
                logger.error("获取MqttMessageReceiveService失败: {}", e.getMessage());
            }
        }
        
        // 使用服务处理消息
        if (mqttMessageReceiveService != null) {
            mqttMessageReceiveService.processMessage(topic, message);
        } else {
            // 降级处理
            logger.info("处理消息：主题 - {}，内容 - {}", topic, message);
        }
    }

    /**
     * 消息发送完成处理
     *
     * @param iMqttDeliveryToken token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("消息发送成功");
    }
} 